<template>
  <view class="message-container">
    <!-- 搜索栏区域 -->
    <view class="search-wrapper">
      <SearchBar placeholder="搜索聊天记录" @search="handleSearch" />
    </view>
    
    <!-- 消息类型导航 -->
    <!-- <view class="message-nav">
      <view class="nav-item active">
        <text>聊天</text>
      </view>
      <view class="nav-item">
        <text>通知</text>
      </view>
      <view class="nav-item">
        <text>公告</text>
      </view>
    </view> -->
    
    <!-- 消息列表区域 -->
    <view class="message-list">
      <uni-list v-for="item in sessionList" :key="item.id">
        <uni-list-chat
          :title="item.title"
          :note="item.lastMessage"
          :time="formatMessageTime(item.lastTime)"
          :avatar-circle="true"
          :show-badge="item.unreadCount > 0"
          :badge-text="item.unreadCount.toString()"
          badgePositon="left"
          :clickable="true"
          @click="goChat(item)"
        >
          <template v-slot:default>
            <view class="chat-custom-right">
              <view class="chat-tags" v-if="item.tags">
                <text>{{ item.tags }}</text>
              </view>
            </view>
          </template>
        </uni-list-chat>
      </uni-list>
    </view>
    
    <!-- 没有更多消息提示 -->
    <view class="no-more-messages" v-if="!sessionList.length">
      <text>没有更多消息了</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useChatStore } from '../../store/chatStore'
import SearchBar from '../../components/SearchBar.vue'

const chatStore = useChatStore()
const { sessionList } = storeToRefs(chatStore)

onMounted(async () => {
  try {
    await chatStore.loadSessionList()
  } catch (error) {
    uni.showToast({
      title: '获取消息列表失败',
      icon: 'none'
    })
  }
})

const handleSearch = (value) => {
}

const goChat = (item) => {
  let targetId;
  try {
    targetId = parseInt(item.targetId);
    if (isNaN(targetId)) {
      uni.showToast({
        title: '无效的聊天ID',
        icon: 'none'
      });
      return;
    }
  } catch (error) {
    uni.showToast({
      title: '无效的聊天ID',
      icon: 'none'
    });
    return;
  }
  
  try {
    const itemData = encodeURIComponent(JSON.stringify({
      targetId: targetId,
      title: item.title || '聊天'
    }));
    
    uni.navigateTo({
      url: `/pages/message/components/chat?data=${itemData}`,
    });
  } catch (error) {
    uni.showToast({
      title: '跳转失败',
      icon: 'none'
    });
  }
}

// 格式化消息时间
const formatMessageTime = (timeString) => {
  if (!timeString) return ''
  
  const messageDate = new Date(timeString)
  const now = new Date()
  
  // 今天的消息只显示时间
  if (messageDate.toDateString() === now.toDateString()) {
    return messageDate.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  
  // 昨天的消息显示"昨天"
  const yesterday = new Date(now)
  yesterday.setDate(now.getDate() - 1)
  if (messageDate.toDateString() === yesterday.toDateString()) {
    return '昨天'
  }
  
  // 一周内的消息显示星期几
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  const diffDays = Math.round((now - messageDate) / (1000 * 60 * 60 * 24))
  if (diffDays < 7) {
    return `星期${weekDays[messageDate.getDay()]}`
  }
  
  // 其他情况显示日期
  return messageDate.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.message-container {
  min-height: 100vh;
  background-color: $bg-color-white;
  padding-bottom: env(safe-area-inset-bottom);
  
  .search-wrapper {
    position: sticky;
    top: 0;
    z-index: 99;
    padding: $spacing-md;
    background: linear-gradient(to right, #00b578, #07c160);
    border-bottom: 1px solid $border-color;
  }
  
  .message-list {
    padding: 0;
    
    :deep(.uni-list) {
      margin-bottom: 1px;
      overflow: hidden;
      background: $bg-color-white;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .uni-list-chat {
        background-color: $bg-color-white;
        padding: $spacing-md;
        position: relative;
        
        &:active {
          background-color: $bg-color-light;
        }

        &::after {
          content: '';
          position: absolute;
          left: $spacing-md;
          right: 0;
          bottom: 0;
          height: 1px;
          background-color: $border-color;
          transform: scaleY(0.5);
        }
        
        .uni-list-chat__header {
          margin-right: $spacing-md;
          
          .uni-list-chat__header-image {
            width: 88rpx;
            height: 88rpx;
            border-radius: 50%;
            border: none;
            background-color: $bg-color-light;
          }
        }
        
        .uni-list-chat__content {
          flex: 1;
          overflow: hidden;
          
          .uni-list-chat__content-title {
            font-size: 32rpx;
            font-weight: bold;
            color: $text-color;
            margin-bottom: $spacing-xs;
          }
          
          .uni-list-chat__content-note {
            font-size: 28rpx;
            color: $text-color-secondary;
            width: 420rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        
        .chat-custom-right {
          display: flex;
          align-items: center;
          
          .chat-tags {
            background: $primary-color;
            padding: 4rpx $spacing-sm;
            border-radius: $radius-sm;
            margin-right: $spacing-xs;
            
            text {
              font-size: 24rpx;
              color: $bg-color-white;
              font-weight: 500;
            }
          }
        }
        
        .uni-list-chat__badge {
          background: $warning-color;
          min-width: 32rpx;
          height: 32rpx;
          padding: 0 $spacing-xs;
          border-radius: 16rpx;
          font-size: 24rpx;
          line-height: 32rpx;
          font-weight: 500;
          color: $bg-color-white;
        }
        
        .uni-list-chat__time {
          font-size: 24rpx;
          color: $text-color-light;
          margin-top: $spacing-xs;
        }
      }
    }
  }
  
  .no-more-messages {
    text-align: center;
    padding: $spacing-lg 0;
    
    text {
      font-size: 28rpx;
      color: $text-color-light;
      background: $bg-color-light;
      padding: $spacing-sm $spacing-md;
      border-radius: $radius-md;
    }
  }
}

// 添加动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

:deep(.uni-list) {
  animation: fadeIn 0.3s ease-out;
}
</style>